<template>
  <div>
    <!--条件筛选-->
    <TopFilter ref="topFilter" :list="topFilterList" :cols="3" labelWidth="110" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <button-area :style="{ paddingLeft: '80px' }"></button-area>
    <FilterTable
      ref="table"
      columnsRef="testindex"
      :columns="columns"
      :fetchapi="fetchApi"
      :isSelectColumn="false"
      :params="fetchParams"
      :datakey="'records'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectData"
      :isExportExcel2="true"
      exportFileName="物流单明细.xlsx"
    >
      <template slot="controls" slot-scope="props">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="openimportPjDialog()">模板导入</el-button>
        <!-- <el-button size="small" type="primary"  @click="exportClick">导出</el-button> -->
      </template>
    </FilterTable>
    <BaseDialog :visible.sync="visibleDrawer" :title="title" width="80vw" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <carrierTrace v-model="initData" :type="handleType" :rowData="formData" @close="infoClose" />
    </BaseDialog>
    <BaseDialog style="min-height: 80vh;" :visible.sync="visibleImportPeij" width="80vw" title="模板导入" destroyOnClose  :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '50px' }">
      <ExcelImport ref="import" template-file-name="物流信息维护导入模板.xlsx" :importRules="importRules" :onComplete="importComplete" @close="visibleImportPeij = false" />
    </BaseDialog>
    <!-- <BaseDialog title="服务商查询" :visible.sync="isShowSearchCustomer" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <SearchCustomer :customerNo="kehuxuanze" @close="isShowSearchCustomer = false" @addCustomerCode="confirmSearchCustomer" />
    </BaseDialog> -->

    <BaseDialog
      :visible.sync="issearch"
      :title="'服务商查询'"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <ownerSeacher  @close="dealercloseHandler" />
    </BaseDialog>
  </div>
</template>

<script>
  import { dictionary } from '@/utils/dictMixin';
  import { getShipmentData ,importTraceInfo,compareWsName,compareNoWl,compareTraceNoWl,exporturl} from '@/api/partsmanage/carrierTraceRepair/query';
  import ExcelImport from '@/components/ExcelImport';
  import carrierTrace from './carrierTrace';
  import SearchCustomer from './SearchCustomer';
  import {numberCheck,banWord } from '@/utils/validate';
import ownerSeacher from '@/pages/partsmanage/claim/approve/ownerSeacher';
  export default {
    name: 'carrierTraceRepairindex',
    components: { carrierTrace, ExcelImport, SearchCustomer,ownerSeacher},
    mixins: [dictionary],
    data() {
      return {
        topFilterList: this.createTopFilterList(),
        fetchParams: { xhrAbort: true },
        columns: this.createTableColumns(),
        fetchApi: getShipmentData,
        dealerCode: '',
        kehuxuanze: '',
        visibleDrawer: false,
        visibleImportPeij: false,
        isShowSearchCustomer: false,
        handleType: '',
        initData: {},
        formData: {},
        wsNameList:[],
        fyNoList:[],
        TraceNoList:[],
        issearch: false,
        title: "",
        importRules: [
          { prop: 'jhNo', title: '交货单号', rule: { required: true, message: '交货单号必填' } },
          {
            prop: 'planJhDate',
            title: '预计到货时间',
          },
          { prop: 'wsName', title: '物流商代码', rule: { required: true, message: '物流商代码为必填项' } },
          { prop: 'traceNo', title: '物流单号', rule: { required: true, message: '物流单号为必填项' } },
        ]
      }
    },
    mounted() {
      // 分页
      this.BaseTable = this.$refs.table.$refs.pageTable;
      this.queryAllWsName();
      this.queryAllfyNo();
      this.queryAllTranceNo();
    },



    methods: {
      seacherFun(){
        this.issearch = true
      },
      dealercloseHandler(val){
        if(val){
          this.topFilterList.find(x=>x.fieldName=='dealerCode').initialValue=val.dealerCode;
          this.topFilterList.find(x=>x.fieldName=='dealerName').initialValue=val.dealerShortname;
        }
        this.issearch=false;
      },
      createTopFilterList() {
        return [
          {
            type: 'INPUT',
            label: '服务商代码',
            fieldName: 'dealerCode',
            placeholder: '请选择',
            unitRender: () => {
              return (
                <div>
                  <el-button icon="el-icon-search" onClick={() => this.seacherFun()}></el-button>
                </div>
              );
            }
          },
          {
            type: 'INPUT',
            label: '服务商简称',
            fieldName: 'dealerName',
            placeholder: '请输入',
          },
          {
            type: 'INPUT',
            label: '备件订单号:',
            fieldName: 'cgNo',
            rules: [{ validator: banWord, trigger: 'blur' },{ max: 20, message: '长度在20个字符以内', trigger: 'blur' }],
          },
          {
            type: 'RANGE_DATE',
            label: '发运日期',
            initialValue: '',
            fieldName: 'startTime|endTime',
            valueFormat: 'yyyy-MM-dd',
            placeholder: '请选择'
          },
          {
            type: 'INPUT',
            label: '交货单号:',
            fieldName: 'bsysdh'
          },
          {
            type: 'INPUT',
            label: '物流单号:',
            fieldName: 'traceNo'
          },
          // {
          //   type: 'INPUT',
          //   label: '联系人:',
          //   fieldName: 'person',
          //   rules: [{max: 8, message: '长度在8个字符以内', trigger: 'blur' }],
          // },
          // {
          //   type: 'INPUT',
          //   label: '联系电话:',
          //   fieldName: 'phone',
          //   rules: [{validator: numberCheck, trigger: 'blur' }, {max: 12, message: '长度在12个字符以内', trigger: 'blur' }],
          // },
          {
            type: 'SELECT',
            label: '是否维护',
            fieldName: 'purchaseStatus',
            itemList: this.createDictList('3043'),
            // itemList: [{text: '未维护', value: '30431001'},{text: '已维护', value: '30431002'}],
            initialValue:30431001,
            placeholder: '请选择...',
            clearable:false
          },
        ]
      },
      createTableColumns() {
        return [
          {
            title: '序号',
            dataIndex: 'index',
            width: 70,
            fixed: 'left',
            sorter: true,
            render: props => {
              return <span>{props.row.index + 1}</span>;
            }
          },
          {
            title: '操作',
            dataIndex: 'column-action',
            width: 50,
            fixed: 'left',
            render: (props, h) => {
              const { getBtnValue,getBtnInfo} = this
              const btnVal = getBtnValue(props.row)
              const infoVal = getBtnInfo(props.row)
              return (
               <div>
                 <multiuse-button isShow={Boolean(btnVal)} size="mini" type="text" onClick={() => this.editHandle(props.row, 'edit')}>
                 修改
                 </multiuse-button>
                 <multiuse-button isShow={Boolean(infoVal)} size="mini" type="text" onClick={() => this.editHandle(props.row,'info')}>
                  明细
                 </multiuse-button>
               </div>
            );
            }
          },
          {
            title: '服务商代码',
            dataIndex: 'companyCode',
            sorter: true,
          },
          {
            title: '服务商名称',
            dataIndex: 'companyName',
            sorter: true,
            width: 200
          },
          {
            title: '是否维护',
            dataIndex: 'WLSTATUS',
            filter: true,
            sorter: true,
            dictItems:this.createDictList('3043'),
            // render: props => {
            //   return <span>{this.createDictText(props.row.WLSTATUS, '3043')}</span>;
            // }
          },
          {
            title: '备件订单号',
            dataIndex: 'cgNo',
            sorter: true,
            width: 185
          },
          {
            title: '物流商代码',
            dataIndex: 'wsCode',
            sorter: true,
            width: 180
          },
          {
            title: '交货单号',
            dataIndex: 'jhNo',
            sorter: true,
          },
          {
            title: '交货单来源',
            dataIndex: 'zjhdly',
            sorter: true,
            dictItems: this.createDictList('3056')
          },
          {
            title: '物流公司',
            dataIndex: 'wsName',
            sorter: true,
          },
          {
            title: '物流单号',
            dataIndex: 'traceNo',
            sorter: true,
            width: 180
          },
          {
            title: '预计交货时间',
            dataIndex: 'planJhDate',
            dateFormat: 'yyyy-MM-dd HH:mm:ss',
            sorter: true,
            width: 150
          },
          {
            title: '联系人',
            dataIndex: 'wsPerson',
            sorter: true,
            width: 180
          },
          {
            title: '联系电话',
            dataIndex: 'wsPhone',
            sorter: true,
            width: 180
          },
          {
            title: '发运日期',
            dataIndex: 'fyDate',
            dateFormat: 'yyyy-MM-dd HH:mm:ss',
            sorter: true,
            width: 150
          },
          {
            title: '备注',
            dataIndex: 'remark',
            sorter: true,
            width: 180,
          },
          {
            title: '订单状态',
            dataIndex: 'XSDJZT',
            sorter: true,
            width: 180,
            hidden:true
          }
        ]
      },
      editHandle(row, type) {
        this.title = '物流信息修改';
        this.formData = row;
        this.formData.type = type;
        this.visibleDrawer = true;
      },
      changeHandle(val) {
        // this.fetchParams = Object.assign({}, val);
        val.endTime && (val.endTime = val.endTime.split(' ')[0] + ' 23:59:59');
        this.fetchParams = Object.assign({},val);
      },
      collapseHandle() {
        this.$nextTick(() => {
          this.BaseTable.EXECUTE_RESET_HEIGHT();
        });
      },
      async confirmSearchCustomer(row) {
        this.rowData = row[0];
        this.topFilterList.find(x => x.fieldName == 'companyCode').initialValue = row[0].dealerCode;
        this.topFilterList.find(x => x.fieldName == 'companyName').initialValue = row[0].dealerShortname;
      },
      async queryAllWsName() {
        let res = await compareWsName();
        var li=JSON.stringify(res,["data"]);
        var kds=JSON.parse(li);
        this.wsNameList=kds.data;
      },
      async exportClick() {
        let json = Object.assign({}, { CODE: 'CODE_00000265' }, this.fetchParams);
        let res = await exporturl(json);
        if (res.resultCode == 200) {
          this.$router.push('/admin/auth/oem/downloadCenter');
        }
      },
      getBtnValue(item) {
        //通过单据状态来的，此处保留万一哪天需要重复编辑
        // if(item.XSDJZT!=='30141003'&&item.XSDJZT!=='30141004'){
        //   return true;
        // }else{
        //   return false;
        // }

        if(item.WLSTATUS!=='30431002'){
          return true;
        }else{
          return false;
        }
      },
      getBtnInfo(item) {
        //同理
        // if(item.XSDJZT==='30141003'||item.XSDJZT==='30141004'){
        //     return true;
        // }else{
        //     return false;
        // }
        if(item.WLSTATUS!=='30431001'){
          return true;
        }else{
          return false;
        }
      },
      async queryAllfyNo() {
        let res = await compareNoWl();
        this.fyNoList=res.data;
      },

      async queryAllTranceNo() {
        let res = await compareTraceNoWl();
        this.TraceNoList=res.data;
      },
      openimportPjDialog() {
        this.visibleImportPeij = true;
      },
      selectData(val) {
        this.tableData = val;
      },
      //导入
      async importComplete(datas, callback) {
        this.queryAllWsName();
        this.queryAllTranceNo();
        await this.queryAllfyNo();
        //获取当前日期

        const errorData = [];
        datas.forEach((item, index1) => {
          const indexarr = [];
          datas.forEach((i, index2) => {
            if (i.cgNo === item.cgNo && i.sapNo === item.sapNo && i.jhNo === item.jhNo &&index1 !== index2) {
              indexarr.push(index2 + 1);
            }
          });
          if (indexarr.length) {
            errorData.push({
              rownum: index1 + 1,
              errormsg: `与第${indexarr.join(',')}行物流信息重复`
            });
          }
          //判断日期，如果日期输入就校验
          if(item.planJhDate){
            let d = new Date();
            let nowYear1 = d.getFullYear();
            let nowMonth1 = d.getMonth() + 1  //月，月是从0开始的所以+1
            let nowDate1 = d.getDate() //日
            nowMonth1 = nowMonth1 < 10 ? "0" + nowMonth1 : nowMonth1 //小于10补0
            nowDate1 = nowDate1 < 10 ? "0" + nowDate1 : nowDate1 //小于10补0
            var regex = /^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/;
            if (regex.test(item.planJhDate)) {
              if (item.planJhDate < `${nowYear1}-${nowMonth1}-${nowDate1}`) {
                errorData.push({
                  rownum: index1 + 1,
                  errormsg: `预计到货日期不能小于当前日期`
                });
              }
          }
          }else{
            errorData.push({
              rownum: index1 + 1,
              errormsg: `日期格式不符，应该为yyyy-MM-dd`
            });
          }
          if(!item.jhNo){
            errorData.push({
              rownum: index1 + 1,
              errormsg: `交货单为必填项，导入模板请填写交货单号`
            });
          }
          if(!this.fyNoList.find(x=>x.BSYSDH===item.jhNo)){
            errorData.push({
              rownum: index1 + 1,
              errormsg: item.jhNo+`该交货单号无法关联相应的发运单信息`
            });
          }else if(item.wsName&&!this.wsNameList.includes(item.wsName)){
            errorData.push({
              rownum: index1 + 1,
              errormsg: item.wsName+`物流商编码信息尚未维护请修改后再试试`
            });
          }
            if(item.traceNo&&this.TraceNoList.find(x=>x.TRACE_NO===item.traceNo&&x.JH_NO!=item.jhNo)){
              errorData.push({
                rownum: index1 + 1,
                errormsg: item.traceNo+`存在相同的物流单号，请重新填写物流单号`
              });
            }
        });
        if (errorData.length) {
          callback(errorData);
        } else {
          importTraceInfo(datas).then(res => {
            if (res.resultCode == 200) {
              if (res.data) { // 0 = false null = false
                callback(res.data);
              } else {
                this.$notify.success({ title: '提示信息', message: '批量导入成功' });
                this.fetchParams = {...this.fetchParams}
                this.visibleImportPeij = false
                callback();
              }
            } else {
              callback([{ errormsg: '服务器运行异常' }]);
            }
          });
        }
      },
      infoClose(rData) {
        this.visibleDrawer = false;
        if (rData.type === 'refresh') {
          // 重新加载
          this.fetchParams = { ...this.fetchParams };
        }
      }
    }
  }
</script>
